const Parse = require('parse/node');
const MaterialObj = Parse.Object.extend("AutoBorrow_Materials");
const CategoryObj = Parse.Object.extend("AutoBorrow_Categories");
const ApplicationObj = Parse.Object.extend("AutoBorrow_Applications");
const RepairObj = Parse.Object.extend("AutoBorrow_Repairs");
const CabinetGridObj = Parse.Object.extend("AutoBorrow_CabinetGrids");
const ParseHelper = require('../helpers/parse');
const ExcelService = require("./excel");
const moment = require('moment');
const _ = require('lodash');

/**
 * 物料管理服务 - 增强版本
 * 支持条码管理、库存管理、申领管理、报修管理
 */

// 物料状态
const MATERIAL_STATUS = {
    AVAILABLE: 'available',    // 可用
    BORROWED: 'borrowed',      // 已借出
    REPAIRING: 'repairing',    // 维修中
    DAMAGED: 'damaged',        // 损坏
    RETIRED: 'retired'         // 已退役
};

// 申领状态
const APPLICATION_STATUS = {
    PENDING: 'pending',        // 待审批
    APPROVED: 'approved',      // 已通过
    REJECTED: 'rejected',      // 已拒绝
    COMPLETED: 'completed',    // 已完成
    CANCELLED: 'cancelled'     // 已取消
};

// 报修状态
const REPAIR_STATUS = {
    SUBMITTED: 'submitted',    // 已提交
    PROCESSING: 'processing',  // 处理中
    COMPLETED: 'completed',    // 已完成
    CANCELLED: 'cancelled'     // 已取消
};

/**
 * 创建物料类别
 * @param {Object} categoryData - 类别数据
 * @returns {Promise<Object>} 创建结果
 */
async function createCategory(categoryData) {
    try {
        const category = new CategoryObj();
        category.set('name', categoryData.name);
        category.set('description', categoryData.description || '');
        category.set('hasBarcode', categoryData.hasBarcode || false);
        category.set('isActive', true);
        category.set('createdAt', new Date());
        
        await category.save(null, { useMasterKey: true });
        
        return {
            success: true,
            category: ParseHelper.toJSON(category),
            message: '类别创建成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 创建物料
 * @param {Object} materialData - 物料数据
 * @returns {Promise<Object>} 创建结果
 */
async function createMaterial(materialData) {
    try {
        // 验证必填字段
        if (!materialData.name || !materialData.categoryId) {
            throw new Error('物料名称和类别为必填项');
        }

        // 检查条码是否唯一（如果有条码）
        if (materialData.barcode) {
            const existingMaterial = await getMaterialByBarcode(materialData.barcode);
            if (existingMaterial) {
                throw new Error('条码已存在');
            }
        }

        const material = new MaterialObj();
        material.set('name', materialData.name);
        material.set('description', materialData.description || '');
        material.set('categoryId', materialData.categoryId);
        material.set('barcode', materialData.barcode || '');
        material.set('deviceId', materialData.deviceId || '');
        material.set('specifications', materialData.specifications || '');
        material.set('price', Number(materialData.price) || 0);
        material.set('totalCount', Number(materialData.totalCount) || 0);
        material.set('availableCount', Number(materialData.totalCount) || 0);
        material.set('borrowedCount', 0);
        material.set('status', MATERIAL_STATUS.AVAILABLE);
        material.set('location', materialData.location || '');
        material.set('supplier', materialData.supplier || '');
        material.set('purchaseDate', materialData.purchaseDate || null);
        material.set('warrantyPeriod', materialData.warrantyPeriod || 0);
        material.set('isActive', true);
        material.set('createdAt', new Date());
        material.set('updatedAt', new Date());
        
        await material.save(null, { useMasterKey: true });
        
        return {
            success: true,
            material: ParseHelper.toJSON(material),
            message: '物料创建成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 批量创建物料
 * @param {Array} materialsData - 物料数据数组
 * @returns {Promise<Object>} 批量创建结果
 */
async function batchCreateMaterials(materialsData) {
    try {
        const results = {
            success: 0,
            failed: 0,
            errors: []
        };

        for (const materialData of materialsData) {
            const result = await createMaterial(materialData);
            if (result.success) {
                results.success++;
            } else {
                results.failed++;
                results.errors.push({
                    name: materialData.name,
                    error: result.error
                });
            }
        }

        return {
            success: true,
            results,
            message: `成功创建 ${results.success} 个物料，失败 ${results.failed} 个物料`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 根据条码获取物料
 * @param {string} barcode - 条码
 * @returns {Promise<Object>} 物料信息
 */
async function getMaterialByBarcode(barcode) {
    try {
        const query = new Parse.Query(MaterialObj);
        query.equalTo('barcode', barcode);
        query.notEqualTo('isDeleted', true);
        
        const material = await query.first({ useMasterKey: true });
        return material ? ParseHelper.toJSON(material) : null;
    } catch (error) {
        throw new Error('获取物料信息失败: ' + error.message);
    }
}

/**
 * 获取物料列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 物料列表
 */
async function getMaterialList(options = {}) {
    try {
        const {
            categoryId,
            status,
            page = 1,
            limit = 10,
            search,
            sortBy = 'createdAt',
            sortOrder = 'desc'
        } = options;

        const query = new Parse.Query(MaterialObj);
        query.notEqualTo('isDeleted', true);

        // 类别筛选
        if (categoryId) {
            query.equalTo('categoryId', categoryId);
        }

        // 状态筛选
        if (status) {
            query.equalTo('status', status);
        }

        // 搜索筛选
        if (search) {
            const searchQuery1 = new Parse.Query(MaterialObj);
            searchQuery1.contains('name', search);
            
            const searchQuery2 = new Parse.Query(MaterialObj);
            searchQuery2.contains('barcode', search);
            
            const searchQuery3 = new Parse.Query(MaterialObj);
            searchQuery3.contains('deviceId', search);
            
            query._orQuery([searchQuery1, searchQuery2, searchQuery3]);
        }

        // 排序
        if (sortOrder === 'desc') {
            query.descending(sortBy);
        } else {
            query.ascending(sortBy);
        }

        // 分页
        const skip = (page - 1) * limit;
        query.skip(skip);
        query.limit(limit);

        // 获取总数
        const countQuery = new Parse.Query(MaterialObj);
        countQuery.notEqualTo('isDeleted', true);
        if (categoryId) countQuery.equalTo('categoryId', categoryId);
        if (status) countQuery.equalTo('status', status);

        const [materials, total] = await Promise.all([
            query.find({ useMasterKey: true }),
            countQuery.count({ useMasterKey: true })
        ]);

        return {
            success: true,
            materials: materials.map(material => ParseHelper.toJSON(material)),
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 更新物料库存
 * @param {string} materialId - 物料ID
 * @param {number} quantity - 数量变化
 * @param {string} operation - 操作类型 (add/subtract)
 * @returns {Promise<Object>} 更新结果
 */
async function updateMaterialStock(materialId, quantity, operation = 'add') {
    try {
        const material = MaterialObj.createWithoutData(materialId);
        
        if (operation === 'add') {
            material.increment('totalCount', quantity);
            material.increment('availableCount', quantity);
        } else if (operation === 'subtract') {
            material.increment('totalCount', -quantity);
            material.increment('availableCount', -quantity);
        }
        
        material.set('updatedAt', new Date());
        await material.save(null, { useMasterKey: true });

        return {
            success: true,
            message: '库存更新成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 创建申领申请
 * @param {Object} applicationData - 申请数据
 * @returns {Promise<Object>} 创建结果
 */
async function createApplication(applicationData) {
    try {
        const application = new ApplicationObj();
        application.set('applicantId', applicationData.applicantId);
        application.set('materials', applicationData.materials || []);
        application.set('purpose', applicationData.purpose || '');
        application.set('expectedReturnDate', applicationData.expectedReturnDate || null);
        application.set('status', APPLICATION_STATUS.PENDING);
        application.set('createdAt', new Date());
        application.set('updatedAt', new Date());
        
        await application.save(null, { useMasterKey: true });
        
        return {
            success: true,
            application: ParseHelper.toJSON(application),
            message: '申请提交成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 审批申请
 * @param {string} applicationId - 申请ID
 * @param {Object} approvalData - 审批数据
 * @returns {Promise<Object>} 审批结果
 */
async function approveApplication(applicationId, approvalData) {
    try {
        const application = ApplicationObj.createWithoutData(applicationId);
        application.set('status', approvalData.status);
        application.set('approverId', approvalData.approverId);
        application.set('approvalComment', approvalData.comment || '');
        application.set('approvedAt', new Date());
        application.set('updatedAt', new Date());
        
        await application.save(null, { useMasterKey: true });
        
        // 如果审批通过，更新物料状态
        if (approvalData.status === APPLICATION_STATUS.APPROVED) {
            // 这里可以添加更新物料状态的逻辑
            // 例如：将物料标记为已借出状态
        }
        
        return {
            success: true,
            message: '审批完成'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 创建报修申请
 * @param {Object} repairData - 报修数据
 * @returns {Promise<Object>} 创建结果
 */
async function createRepair(repairData) {
    try {
        const repair = new RepairObj();
        repair.set('reporterId', repairData.reporterId);
        repair.set('materialId', repairData.materialId);
        repair.set('deviceId', repairData.deviceId || '');
        repair.set('problemDescription', repairData.problemDescription || '');
        repair.set('priority', repairData.priority || 'normal');
        repair.set('status', REPAIR_STATUS.SUBMITTED);
        repair.set('createdAt', new Date());
        repair.set('updatedAt', new Date());
        
        await repair.save(null, { useMasterKey: true });
        
        return {
            success: true,
            repair: ParseHelper.toJSON(repair),
            message: '报修申请提交成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 处理报修申请
 * @param {string} repairId - 报修ID
 * @param {Object} processData - 处理数据
 * @returns {Promise<Object>} 处理结果
 */
async function processRepair(repairId, processData) {
    try {
        const repair = RepairObj.createWithoutData(repairId);
        repair.set('status', processData.status);
        repair.set('processerId', processData.processerId);
        repair.set('processComment', processData.comment || '');
        repair.set('processedAt', new Date());
        repair.set('updatedAt', new Date());
        
        await repair.save(null, { useMasterKey: true });
        
        return {
            success: true,
            message: '报修处理完成'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取库存统计
 * @returns {Promise<Object>} 库存统计
 */
async function getInventoryStats() {
    try {
        const query = new Parse.Query(MaterialObj);
        query.notEqualTo('isDeleted', true);
        
        const materials = await query.find({ useMasterKey: true });
        
        const stats = {
            totalMaterials: materials.length,
            totalStock: 0,
            availableStock: 0,
            borrowedStock: 0,
            categoryStats: {}
        };
        
        materials.forEach(material => {
            const data = ParseHelper.toJSON(material);
            stats.totalStock += data.totalCount || 0;
            stats.availableStock += data.availableCount || 0;
            stats.borrowedStock += data.borrowedCount || 0;
            
            // 按类别统计
            const categoryId = data.categoryId;
            if (!stats.categoryStats[categoryId]) {
                stats.categoryStats[categoryId] = {
                    count: 0,
                    totalStock: 0,
                    availableStock: 0,
                    borrowedStock: 0
                };
            }
            stats.categoryStats[categoryId].count++;
            stats.categoryStats[categoryId].totalStock += data.totalCount || 0;
            stats.categoryStats[categoryId].availableStock += data.availableCount || 0;
            stats.categoryStats[categoryId].borrowedStock += data.borrowedCount || 0;
        });
        
        return {
            success: true,
            stats
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 导入物料Excel文件
 * @param {string} filePath - 文件路径
 * @param {Object} options - 导入选项
 * @returns {Promise<Object>} 导入结果
 */
async function importMaterialsFromExcel(filePath, options = {}) {
    try {
        const {
            nameRowNumber = 1,
            firstDataRowNumber = 2,
            fieldsMapping = {}
        } = options;

        const materialsData = await ExcelService.parseExcelFileFirstSheet(
            filePath,
            nameRowNumber,
            firstDataRowNumber
        );

        if (!materialsData || materialsData.length === 0) {
            throw new Error('Excel文件没有有效数据');
        }

        // 数据映射
        const mappedMaterialsData = materialsData.map(materialData => {
            const mappedData = {};
            Object.keys(materialData).forEach(key => {
                const dbFieldName = fieldsMapping[key] || key;
                mappedData[dbFieldName] = materialData[key];
            });
            return mappedData;
        });

        // 批量创建物料
        const result = await batchCreateMaterials(mappedMaterialsData);
        
        return result;
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

module.exports = {
    createCategory,
    createMaterial,
    batchCreateMaterials,
    getMaterialByBarcode,
    getMaterialList,
    updateMaterialStock,
    createApplication,
    approveApplication,
    createRepair,
    processRepair,
    getInventoryStats,
    importMaterialsFromExcel,
    MATERIAL_STATUS,
    APPLICATION_STATUS,
    REPAIR_STATUS
};
